<template>
  <div class="main">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1 class="page-title">收费项目定义</h1>
      <div class="header-controls">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增
        </el-button>
        <div class="search-container">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入收费项目名称"
            clearable
            @keyup.enter="handleSearch"
            @clear="handleSearch"
          />
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
          </el-button>
        </div>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="content-area">
      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="收费项目名称" />
        <el-table-column prop="chargetypeName" label="收费类别" />
        <el-table-column prop="remarks" label="备注">
          <template #default="{ row }">
            {{ row.remarks || "--" }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              :icon="Edit"
              class="edit-btn"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="prev, pager, next, sizes, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="560px"
      @close="resetForm"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="收费项目名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入收费项目名称" />
        </el-form-item>
        <el-form-item label="收费类别" prop="chargetypeId">
          <el-select
            v-model="form.chargetypeId"
            placeholder="请选择收费类别"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in chargeTypeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-model="form.remarks"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit"
          >确定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Search, Edit } from "@element-plus/icons-vue";
import {
  getChargeItemList,
  addChargeItem,
  updateChargeItem,
  deleteChargeItem,
  type ChargeItemItem,
  type ChargeItemListParams,
  type ChargeItemAddParams,
  type ChargeItemUpdateParams,
  type ChargeItemDeleteParams
} from "@/api/chargeItem";
import {
  getChargeTypeList,
  type ChargeTypeItem,
  type ChargeTypeListParams
} from "@/api/chargeType";

defineOptions({ name: "ChargeItems" });

// 响应式数据
const loading = ref(false);
const submitLoading = ref(false);
const dialogVisible = ref(false);
const dialogTitle = ref("新增收费项目");
const formRef = ref();

// 表格数据
const tableData = ref<ChargeItemItem[]>([]);
const selectedRows = ref<ChargeItemItem[]>([]);

// 搜索表单
const searchForm = reactive({
  name: ""
});

// 分页数据
const pagination = reactive({
  page: 1,
  limit: 10,
  total: 0
});

// 表单数据
const form = reactive({
  id: null as number | null,
  name: "",
  chargetypeId: null as number | null,
  remarks: ""
});

// 收费类别选项
const chargeTypeOptions = ref<ChargeTypeItem[]>([]);

// 表单验证规则
const rules = {
  name: [{ required: true, message: "请输入收费项目名称", trigger: "blur" }],
  chargetypeId: [
    { required: true, message: "请选择收费类别", trigger: "change" }
  ]
};

// 获取收费类别
const loadChargeTypes = async () => {
  try {
    const params: ChargeTypeListParams = {
      page: 0,
      limit: 9999,
      name: ""
    };
    const res = await getChargeTypeList(params);
    if (res && (res as any).data) {
      chargeTypeOptions.value = (res as any).data.list || [];
    }
  } catch (e) {
    console.error("获取收费类别失败:", e);
  }
};

// 获取列表数据
const getList = async () => {
  try {
    loading.value = true;
    const params: ChargeItemListParams = {
      page: pagination.page - 1, // 后端从0开始
      limit: pagination.limit,
      name: searchForm.name
    };

    const response = await getChargeItemList(params);

    if (response && (response as any).data) {
      tableData.value = (response as any).data.list || [];
      pagination.total = (response as any).data.total || 0;
    }
  } catch (error) {
    console.error("获取列表失败:", error);
    ElMessage.error("获取数据失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.page = 1;
  getList();
};

// 新增
const handleAdd = () => {
  dialogTitle.value = "新增收费项目";
  resetForm();
  dialogVisible.value = true;
};

// 编辑
const handleEdit = (row: ChargeItemItem) => {
  dialogTitle.value = "编辑收费项目";
  form.id = row.id;
  form.name = row.name;
  form.chargetypeId = (row as any).chargetypeId ?? null;
  form.remarks = row.remarks || "";
  dialogVisible.value = true;
};

// 删除
const handleDelete = async (row: ChargeItemItem) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除收费项目"${row.name}"吗？`,
      "删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    const params: ChargeItemDeleteParams = { id: row.id } as any;
    const res = (await deleteChargeItem(params)) as any;

    if (res.code === 0) {
      ElMessage.success("删除成功");
      getList();
    } else {
      ElMessage.error(res.message || "删除失败");
    }
  } catch (error: any) {
    if (error !== "cancel") {
      console.error("删除失败:", error);
      if (error.code && error.message) {
        ElMessage.error(error.message);
      } else {
        ElMessage.error("删除失败，请稍后重试");
      }
    }
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    submitLoading.value = true;

    if (form.id) {
      // 编辑
      const params: ChargeItemUpdateParams = {
        id: form.id as number,
        name: form.name,
        chargetypeId: form.chargetypeId as number,
        remarks: form.remarks
      } as any;
      await updateChargeItem(params);
      ElMessage.success("编辑成功");
    } else {
      // 新增
      const params: ChargeItemAddParams = {
        name: form.name,
        chargetypeId: form.chargetypeId as number,
        remarks: form.remarks
      } as any;
      await addChargeItem(params);
      ElMessage.success("新增成功");
    }

    dialogVisible.value = false;
    getList();
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error(form.id ? "编辑失败" : "新增失败");
  } finally {
    submitLoading.value = false;
  }
};

// 重置表单
const resetForm = () => {
  form.id = null;
  form.name = "";
  form.chargetypeId = null;
  form.remarks = "";
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 选择变化
const handleSelectionChange = (selection: ChargeItemItem[]) => {
  selectedRows.value = selection;
};

// 分页大小变化
const handleSizeChange = (val: number) => {
  pagination.limit = val;
  pagination.page = 1;
  getList();
};

// 当前页变化
const handleCurrentChange = (val: number) => {
  pagination.page = val;
  getList();
};

// 组件挂载时获取数据
onMounted(() => {
  loadChargeTypes();
  getList();
});
</script>

<style scoped>
.main {
  min-height: 100vh;
  padding: 20px;
  background-color: #f5f7fa;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px;
  margin-bottom: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgb(0 0 0 / 10%);
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.header-controls {
  display: flex;
  gap: 15px;
  align-items: center;
}

.search-container {
  display: flex;
  gap: 8px;
  align-items: center;
}

.search-container .el-input {
  width: 300px;
}

.content-area {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgb(0 0 0 / 10%);
  padding: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 20px 0;
}

/* 表格样式优化 */
::deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

::deep(.el-table th) {
  background-color: #f8f9fa;
  color: #606266;
  font-weight: 600;
}

::deep(.el-table td) {
  border-bottom: 1px solid #ebeef5;
}

::deep(.el-table .el-button--text) {
  padding: 4px 8px;
  font-size: 14px;
}

/* 分页样式优化 */
::deep(.el-pagination) {
  justify-content: center;
}

::deep(.el-pagination .el-pager li) {
  min-width: 32px;
  height: 32px;
  line-height: 32px;
  margin: 0 2px;
  border-radius: 4px;
}

::deep(.el-pagination .el-pager li.is-active) {
  background-color: #409eff;
  color: white;
}

/* 弹窗样式优化 */
::deep(.el-dialog) {
  border-radius: 8px;
}

::deep(.el-dialog__header) {
  padding: 20px 20px 10px;
  border-bottom: 1px solid #ebeef5;
}

::deep(.el-dialog__body) {
  padding: 20px;
}

::deep(.el-dialog__footer) {
  padding: 10px 20px 20px;
  border-top: 1px solid #ebeef5;
}

/* 按钮样式优化 */
.el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
}

.el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

/* 搜索框样式 */
.search-container .el-input__wrapper {
  border-radius: 4px;
}

.search-container .el-button {
  border-radius: 4px;
  padding: 8px 12px;
}

/* 编辑按钮样式 */
.edit-btn {
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
  border: none;
  border-radius: 6px;
  color: white;
  font-weight: 500;
  padding: 6px 12px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.3);
}

.edit-btn:hover {
  background: linear-gradient(135deg, #66b1ff 0%, #409eff 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.4);
}

.edit-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.3);
}
</style>
